//
//  CityViewController.m
//  BaiTuan
//
//  Created by huiwenjiaoyu on 15/12/23.
//  Copyright © 2015年 YR. All rights reserved.
//

#import "CityViewController.h"
#import "CityModel.h"
#import "AFNetworking.h"
#import "DBManager.h"
#import "City.h"
#import "HomeViewController.h"

@interface CityViewController ()<UITableViewDataSource, UITableViewDelegate, NSFetchedResultsControllerDelegate, UISearchBarDelegate>

@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, copy) NSArray *citys;
@property (nonatomic, strong) NSFetchedResultsController *fetchController;
@property (nonatomic, strong) UITableView *searchResultTableView;

@end

@implementation CityViewController

#pragma mark - 懒加载

- (UITableView *)searchResultTableView
{
    if (_searchResultTableView == nil) {
        _searchResultTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 30, kScreenWidth, kScreenHeight - 30) style:UITableViewStylePlain];
        _searchResultTableView.delegate = self;
        _searchResultTableView.dataSource = self;
        _searchResultTableView.hidden = YES;
        [self.view insertSubview:_searchResultTableView aboveSubview:self.tableView];
    }
    return _searchResultTableView;
}

- (NSFetchedResultsController *)fetchController
{
    if (_fetchController == nil) {
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"City"];
        NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"city_cap" ascending:YES];
        fetchRequest.sortDescriptors = @[sortDescriptor];
        _fetchController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:[[DBManager shareManager] managedObjectContext] sectionNameKeyPath:@"city_cap" cacheName:nil];
        _fetchController.delegate = self;
        [_fetchController performFetch:nil];
    }
    return _fetchController;
}

- (UITableView *)tableView
{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [self.view addSubview:_tableView];
        
    }
    return _tableView;
}

- (UISearchBar *)searchBar
{
    if (_searchBar == nil) {
        _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 64, kScreenWidth, 40)];
        _searchBar.placeholder = @"请输入城市中文名称或者拼音";
        [self.view addSubview:_searchBar];
    }
    return _searchBar;
}

#pragma  mark -

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.translucent = NO;
    [self customHeadView];
    [self tableView];
    
    if (self.fetchController.sections.count == 0) {
        
        [self requestData];
    }
    //    NSLog(@"%@",[[DBManager shareManager] applicationDocumentsDirectory]);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - tableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView == self.tableView) {
        return self.fetchController.sections.count;
    }else{
        
        return 1;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.tableView) {
        
        return [self.fetchController.sections[section] numberOfObjects];
    }else{
        return self.citys.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.tableView) {
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        }
        City *city = [self.fetchController objectAtIndexPath:indexPath];
        cell.textLabel.text = city.city_name;
        return cell;
    }else{
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"searchResultCell"];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"searchResultCell"];
        }
        cell.textLabel.text = [self.citys[indexPath.row] city_name];
        return cell;
    }
}
//tableView 边栏
- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if (tableView == self.tableView) {
        NSMutableArray *arrayM = [NSMutableArray array];
        for (id<NSFetchedResultsSectionInfo> tmp in self.fetchController.sections) {
            
            [arrayM addObject:tmp.name];
        }
        
        return arrayM;
    }else{
        return nil;
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (tableView == self.tableView) {
        
        return [self.fetchController.sections[section] name];
    }else{
        return nil;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (tableView == self.tableView) {
        
        City *city = [[self.fetchController.sections[indexPath.section] objects] objectAtIndex:indexPath.row];
        HomeViewController *vc = (HomeViewController *)self.navigationController.viewControllers[0];
        vc.city = city;
    }else{
        
        City *city = self.citys[indexPath.row];
        HomeViewController *vc = (HomeViewController *)self.navigationController.viewControllers[0];
        vc.city = city;
    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 网络数据申请

- (void)requestData
{
    
    AFHTTPSessionManager *mananer = [AFHTTPSessionManager manager];
    [mananer.requestSerializer setValue:apikey forHTTPHeaderField:@"apikey"];
    
    [mananer GET:cities
      parameters:nil
        progress:^(NSProgress * _Nonnull downloadProgress) {
            
            
        }
         success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
             
//             self.citys = [CityModel citysWithArray:responseObject[@"cities"]];
//             [self.tableView reloadData];
             
             NSArray *cityInfos = [responseObject objectForKey:@"cities"];
             for (NSDictionary *dic in cityInfos) {
                 
                 City *city = [NSEntityDescription insertNewObjectForEntityForName:@"City" inManagedObjectContext:[[DBManager shareManager] managedObjectContext]];
                 city.city_id = dic[@"city_id"];
                 city.city_name = dic[@"city_name"];
                 city.city_pinyin = dic[@"city_pinyin"];
                 city.city_cap = [city.city_pinyin substringToIndex:1];
                 city.short_name = dic[@"short_name"];
                 city.short_pinyin = dic[@"short_pinyin"];
                 
             }
             [[DBManager shareManager] saveContext];
             
         }
         failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
             
             
         }];
}

#pragma mark - fetchController Delegate

- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath
{
    
    if (type == NSFetchedResultsChangeInsert) {
        
        [self.tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}

- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id<NSFetchedResultsSectionInfo>)sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type
{
    
    if (type == NSFetchedResultsChangeInsert) {
        
        [self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
    }
}

- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller
{
    [self.tableView beginUpdates];
}

- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
    [self.tableView endUpdates];
}

#pragma mark - customHeadView

- (void)customHeadView
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 350)];
    view.backgroundColor = [UIColor lightGrayColor];
    
    UISearchBar *searBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth - 15, 30)];
    searBar.placeholder = @"请输入城市的拼音或名称";
    searBar.delegate = self;
    [view addSubview:searBar];
    
    UILabel *Flabel = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(searBar.frame) + 10, 200, 20)];
    Flabel.font = [UIFont systemFontOfSize:15];
    Flabel.text = @"已定位城市";
    [view addSubview:Flabel];
    
    UIButton *Lbtn = [self customButtonWithTitle:@"杭州市"];
    Lbtn.frame = CGRectMake(10, CGRectGetMaxY(Flabel.frame) + 5, 100, 40);
    [view addSubview:Lbtn];
    
    UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(Lbtn.frame) + 5, 200, 20)];
    label2.text = @"最近访问的城市";
    label2.font = [UIFont systemFontOfSize:15];
    [view addSubview:label2];
    
    UIButton *btn = [self customButtonWithTitle:@"杭州市"];
    btn.frame = CGRectMake(10, CGRectGetMaxY(label2.frame) + 5, 100, 40);
    [view addSubview:btn];
    
    UILabel *label3 = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(btn.frame) + 5, 200, 20)];
    label3.font = [UIFont systemFontOfSize:15];
    label3.text = @"热门城市";
    [view addSubview:label3];
    
    NSArray *names = @[@"北京市",@"上海市",@"杭州市",@"成都市",@"郑州市",@"武汉市",@"天津市",@"重庆市",@"西安市"];
    [names enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        CGFloat marg = (kScreenWidth - 10 - 10 - 100 * 3) / 3;
        CGFloat row = idx / 3;
        CGFloat col = idx % 3;
        UIButton *btn2 = [self customButtonWithTitle:obj];
        btn2.frame = CGRectMake(10 + col * (100 + marg), CGRectGetMaxY(label3.frame)+ row * (40 + 10), 100, 40);
        [view addSubview:btn2];
    }];
    
    self.tableView.tableHeaderView = view;
}

- (UIButton *)customButtonWithTitle:(NSString *)title
{
    UIButton *btn = [[UIButton alloc] init];
    btn.backgroundColor = [UIColor whiteColor];
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    return btn;
}

#pragma mark - searchBar Delegate

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    searchBar.showsCancelButton = YES;
    return YES;
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
    self.searchResultTableView.hidden = YES;
    self.citys = nil;
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    searchBar.showsCancelButton = NO;
    [searchBar resignFirstResponder];
    self.searchResultTableView.hidden = YES;
    self.citys = nil;
    searchBar.text = nil;
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if (searchText.length != 0) {
        NSString *str = [NSString stringWithFormat:@"city_pinyin LIKE[c] '%@*'",searchText];
        NSPredicate *predicate = [NSPredicate predicateWithFormat:str];
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"City"];
        fetchRequest.predicate = predicate;
        self.citys = [[[DBManager shareManager] managedObjectContext] executeFetchRequest:fetchRequest error:nil];
        self.searchResultTableView.hidden = NO;
        [self.searchResultTableView reloadData];
    }
    
}



@end
